import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = {
  vus: 10, // 10个虚拟用户
  duration: '1m', // 持续1分钟
  thresholds: {
    http_req_duration: ['p(95)<1000'], // 95%的请求在1秒内完成
    http_req_failed: ['rate<0.1'], // 失败率小于10%
  },
};

const BASE_URL = 'http://localhost:8081/api';

// 测试用户数据
const USERS = [
  { account: 'teacher001', password: 'teacher123' },
  { account: 'student001', password: 'student123' }
];

export default function () {
  // 测试1: 用户登录
  const user = USERS[Math.floor(Math.random() * USERS.length)];
  const loginData = new URLSearchParams({
    account: user.account,
    password: user.password
  });

  const loginResponse = http.post(`${BASE_URL}/users/login`, loginData.toString(), {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  });

  check(loginResponse, {
    '登录成功': (r) => r.status === 200,
    '登录响应时间OK': (r) => r.timings.duration < 1000,
  });

  // 测试2: 获取所有课程
  const coursesResponse = http.get(`${BASE_URL}/courses`);
  
  check(coursesResponse, {
    '获取课程成功': (r) => r.status === 200,
    '课程数据格式正确': (r) => {
      try {
        return Array.isArray(JSON.parse(r.body));
      } catch {
        return false;
      }
    },
  });

  // 测试3: 用户注册 (偶尔执行)
  if (Math.random() < 0.2) { // 20%概率执行注册测试
    const timestamp = Date.now();
    const randomId = Math.floor(Math.random() * 10000);
    const userAccount = `test${timestamp}${randomId}`;
    const newUser = {
      userName: `测试用户_${randomId}`,
      userAccount: userAccount,
      userPassword: 'test123'
    };

    const registerResponse = http.post(`${BASE_URL}/users/register`, JSON.stringify(newUser), {
      headers: { 'Content-Type': 'application/json' },
    });

    check(registerResponse, {
      '注册请求处理': (r) => r.status === 200 || r.status === 409,
    });
  }

  // 只在最后sleep一次，减少等待时间
  sleep(0.5);
}

export function setup() {
  console.log('开始CourseHub API优化压力测试');
  console.log('测试接口: 登录、获取课程、用户注册');
  console.log('优化: 减少sleep时间，提高请求频率');
}

export function teardown() {
  console.log('优化压力测试完成');
}